package com.xb.p3_fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ListviewFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_listview,container,false);
    }

    /*fragment通信方式二：在执行事件的Fragment中添加事件处理*/
    private int img[]={R.id.image0,R.id.image1,R.id.image2,R.id.image3,R.id.image4,R.id.image5,R.id.image6};
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //要填充图片的View的ID
        /*final ImageView img_frag=this.getActivity().findViewById(R.id.image_view);
        for (int i = 0; i < img.length; i++) {
            ImageView iv=this.getActivity().findViewById(img[i]);
            if(iv !=null){
                //为List中的每一个图片添加监听事件
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //点击时，将当前图片的View填充到指定位置
                        ImageView view=(ImageView) v;
                        img_frag.setImageDrawable(view.getDrawable());
                    }
                });
            }
        }*/

        //方式三中的3.进行事件监听
        for (int i = 0; i < img.length; i++) {
            ImageView iv = this.getActivity().findViewById(img[i]);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //通过ListViewEvent接口中的方法来处理，具体的实现在MainActivity中完成
                    listViewEvent.onImageClickListner((ImageView)v);
                }
            });
        }
    }


    /*fragment通信方式三：Fragment与Activity之间进行通信*/
    //方法三:Fragment与Activity的通信
    //1.Fragment中定义接口
    //2.Fragment定义设置接口的方法
    //3.Activity实现接口
    //4.Fragment添加监听,事件处理环节调用事件处理接口,具体操作由Activity进行.
    //5.Activity的onAttach方法中,调用Fragment 设置接口的方法,将自身引用传入
    ListViewEvent listViewEvent;

    //1.Fragment中定义接口
    public interface ListViewEvent{
        public void onImageClickListner(ImageView imageView);
    }

    //2.Fragment定义设置接口的方法
    public void setListViewEvent(ListViewEvent listViewEvent){
        this.listViewEvent=listViewEvent;
    }
}
